package com.github.panchitoboy.shiro.wechat.realm;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.github.panchitoboy.shiro.wechat.filter.WechatJWTAuthenticationToken;
import com.github.panchitoboy.shiro.wechat.repository.AuthenticationService;
import com.github.panchitoboy.shiro.wechat.repository.UserInfo;
import com.github.panchitoboy.shiro.wechat.repository.WechatUserRepository;
import com.thinkgem.jeesite.common.config.Config;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.config.GlobalConst;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.modules.sys.service.SystemService;

import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Service
public class WechatJwtRealm extends AuthorizingRealm {
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier("memberUserService") //指定实现类
	private AuthenticationService authenticationService;
	
	@Autowired
	private WechatUserRepository wechatUserRepository;
	
	@Autowired
	private SystemService systemService;
	
    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null && token instanceof WechatJWTAuthenticationToken;
    }
    /**
     * 验证函数
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    	WechatJWTAuthenticationToken wechatToken = (WechatJWTAuthenticationToken) token;
    	String phoneNumber = wechatToken.getPhoneNumber().toString();
    	String pwd=wechatToken.getPassword();
    	//使用手机号、短信验证码、微信传回的code登录时
    	if(wechatToken.isLogin()) {
    		if (logger.isDebugEnabled()){
    			logger.debug("login submit, phoneNumber: {}", phoneNumber);
    		}
    		
    		//如果是微信模式
    		if(Config.isWechatMode()) {
	    		if(StringUtils.isBlank(wechatToken.getCode())) {
	    			throw new AuthenticationException("请您在微信上登录！或退出当前页面重新进入登录页面");
	    		}
    		}
    		
    		/*if(StringUtils.isBlank(wechatToken.getCaptcha())) {
    			throw new AuthenticationException("请您输入验证码！");
    		}
    		
    		if(CacheUtils.get(GlobalConst.CAPTCHA_CACHE, phoneNumber) == null) {
    			throw new AuthenticationException("您输入的手机号与验证码不相符，请重新登录！");
    		}
    		
    		if (!((String)CacheUtils.get(GlobalConst.CAPTCHA_CACHE, phoneNumber)).equals(wechatToken.getCaptcha())) {
    			throw new AuthenticationException("您输入的手机号与验证码不相符，请重新登录！");
    		}*/
    		//在缓存中获得openId
    		String openId = CacheUtils.get(GlobalConst.WECHAT_USER_CACHE, wechatToken.getCode()) == null ? "" : (String)CacheUtils.get(GlobalConst.WECHAT_USER_CACHE, wechatToken.getCode()) ;
    		
    		UserInfo userInfo = null;
    		
    		//获得用户信息
    		if(Config.isWechatMode()) {
    			//如果是正常模式(非debug模式)下验证openId
				if(StringUtils.isBlank(openId)) {
	    			throw new AuthenticationException("code无效！");
	    		}
				userInfo = authenticationService.getUserInfoByPhoneNumber(wechatToken.getPhoneNumber().toString(), openId);
    		} else {
    			//在调试模式下直接获得用户信息
    			userInfo = authenticationService.getUserInfoByPhoneNumber(wechatToken.getPhoneNumber().toString());
    		}
    		if(userInfo == null) {
    			throw new AuthenticationException("没有该账号");
    		}
    		if(userInfo != null && Global.NO.equals(userInfo.getLoginFlag())) {
    			throw new AuthenticationException("msg:该已帐号禁止登录.");
    		}
    		boolean pwdFlag=systemService.validatePassword(pwd,userInfo.getPassword());
			if(!pwdFlag) {
    			throw new AuthenticationException("输入的用户名或密码错误");
    		}	
    		/*//如果没有信息则注册会员
    		if(userInfo == null) {
    			//在缓存中通过openId获得微信用户信息
    			WxMpUser wxMpUser = (WxMpUser)CacheUtils.get(GlobalConst.WECHAT_USER_CACHE, openId) ;
    			String memberName = wxMpUser == null ? phoneNumber : wxMpUser.getNickname();
    			String genderCode = wxMpUser == null ? "" : wxMpUser.getSexId().toString();
    			userInfo = authenticationService.register(memberName, phoneNumber, genderCode, openId);
    		}*/
    		
    		//创建shiro用户信息
			SimpleAccount account = new SimpleAccount(userInfo, wechatToken.getCredentials(), getName());
            return account;
    		
            //throw new AuthenticationException("没有该用户信息！");
    		
    	} else { //验证token时
    		if(!wechatUserRepository.validateToken(wechatToken.getToken())) {
    			throw new AuthenticationException("Token已失效！");
    		}
    		UserInfo userInfo = authenticationService.getUserInfoByPhoneNumber(wechatToken.getPhoneNumber().toString());
            if (userInfo != null) {
            	SimpleAccount account = new SimpleAccount(userInfo, wechatToken.getToken(), getName());
                return account;
            } else {
            	throw new AuthenticationException("Token已失效！");
            }
    	}
    }

	
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

}
